import {
  Button,
  Card,
  Form,
  Input,
  Radio,
  // Select,
  Space,
  Breadcrumb,
  Upload,
  Modal,
  message,
} from 'antd'
import { Link, useHistory, useParams } from 'react-router-dom'
import { PlusOutlined } from '@ant-design/icons'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'
import { useEffect, useRef, useState } from 'react'
import Channels from '@/components/Channels'
import { useDispatch } from 'react-redux'
import {
  addArticle,
  editArticle,
  getAticleDetail,
} from '@/store/actions/article'

export default function Publish() {
  const [type, setType] = useState(1)
  const [fileList, setFileList] = useState([])
  const fileRef = useRef(fileList)
  const formRef = useRef(null)

  const dispatch = useDispatch()
  const history = useHistory()
  const { id } = useParams()

  const Onpublish = async (draft, values) => {
    const images = fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        return item.response.data.url
      }
    })
    const data = {
      ...values,
      cover: {
        type: type,
        images: images,
      },
    }
    if (id) {
      await dispatch(editArticle(draft, { ...data, id }))
    } else {
      dispatch(addArticle(draft, data))
    }
    history.push('/home/article')
  }
  // 编辑
  useEffect(() => {
    if (!id) return
    dispatch(getAticleDetail(id)).then((res) => {
      console.log(res)
      // 表单的回显
      formRef.current.setFieldsValue({ ...res, type: res.cover.type })
      // 图片的回显
      setType(res.cover.type)
      const list = res.cover.images.map((item) => {
        return { url: item }
      })
      setFileList(list)
      fileRef.current = list
    })
  }, [id, dispatch])

  const changeType = ({ target }) => {
    setType(target.value)
    // console.log(target.value, type)
    setFileList(fileRef.current.slice(0, target.value))
  }

  const changeFileList = ({ fileList }) => {
    // console.log(fileList)
    setFileList(fileList)
    fileRef.current = fileList
    // console.log('type', type)
    formRef.current.validateFields(['type'])
  }

  const [isVisible, setIsVisible] = useState(false)
  const [imgUrl, setImgUrl] = useState(null)

  // 图片预览
  const onPreview = (file) => {
    console.log(file)
    setIsVisible(true)
    setImgUrl(file.url || file.response.data.url)
  }
  // 发布
  const finish = (values) => {
    Onpublish(false, values)
    message.success('操作成功')
  }

  const save = async () => {
    const values = await formRef.current.validateFields()
    Onpublish(true, values)
    message.success('存入草稿成功')
  }

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          ref={formRef}
          initialValues={{ content: '', type: type }}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          size="large"
          onFinish={finish}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '文章标题不能为空' }]}
          >
            <Input style={{ width: 400 }} placeholder="请输入文章标题"></Input>
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '频道不能为空' }]}
            // style={{ width: 300 }}
          >
            <Channels></Channels>
          </Form.Item>
          <Form.Item
            label="封面"
            name="type"
            rules={[
              {
                validator: (_, value) => {
                  // console.log(value)
                  if (fileList.length !== value) {
                    return Promise.reject(new Error(`请上传${value}张图片`))
                  } else {
                    return Promise.resolve()
                  }
                },
              },
            ]}
          >
            <Radio.Group value={type} onChange={changeType}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          {type > 0 && (
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Upload
                style={{ marginTop: 10 }}
                listType="picture-card"
                className="avatar-uploader"
                fileList={fileList}
                name="image"
                onChange={changeFileList}
                action={`${process.env.REACT_APP_URL}upload`}
                maxCount={type}
                onPreview={onPreview}
              >
                {fileList.length < type && <PlusOutlined />}
              </Upload>
            </Form.Item>
          )}
          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '文章内容不能为空' }]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {id ? '确定编辑' : '发布文章'}
              </Button>
              <Button onClick={save}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
      <Modal
        title="预览图片"
        style={{ textAlign: 'center' }}
        visible={isVisible}
        footer={null}
        width={600}
        onCancel={() => {
          setIsVisible(false)
        }}
      >
        <img src={imgUrl} style={{ width: 500 }} alt="" />
      </Modal>
    </div>
  )
}
